<?php

namespace App\Models;

use App\Constant\UserFollowTypeCode;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class UserFollowCacheDay extends Model
{
    protected $table = 'user_follow_cache_day';

    /**
     * 可以被批量赋值的属性。
     * @var array
     */
    protected $fillable = [
        'date',
        'hour',
        'channel',
        'channel_name',
        'type_total'
    ];

    public function cacheDayData($day)
    {
        $today_time = strtotime($day);
        $yesterday_time = strtotime("-1 day", $today_time);
        $start_day = date('Y-m-d H:i:s', $yesterday_time);
        $end_day = date('Y-m=d H:i:s', ($today_time - 1));
        $sql = <<<SQL
    SELECT 
      COUNT(DISTINCT user_id) as total,
      COUNT(finger_print) as pv,
      COUNT(DISTINCT finger_print) as uv,
      channel, type
    FROM 
      user_follows
    WHERE 
      code = 200
    AND created_at BETWEEN '{$start_day}' AND '{$end_day}'
    GROUP BY channel,type
SQL;

        $result = DB::connection('backend')->select($sql);

        //对象转数组
        $result = array_map('get_object_vars', $result);

        if (empty($result)) {
            Log::debug('后台统计数据为空');

            return false;
        }

        $item = $data = [];
        foreach ($result as $value) {
            $item[$value['channel']][] = $value;
        }

        foreach ($item as $k => $it) {
            foreach ($it as $i) {
                switch ($i['type']) {
                    case UserFollowTypeCode::TYPE_USER_LOGIN:
                        $info['login_num'] = $i['total'];
                        break;
                    case UserFollowTypeCode::TYPE_VERIFIED:
                        $info['card_submit'] = $i['total'];
                        break;
                    case UserFollowTypeCode::TYPE_USER_FACE:
                        $info['face_submit'] = $i['total'];
                        break;
                    case UserFollowTypeCode::TYPE_CONTACT:
                        $info['contact_submit'] = $i['total'];
                        break;
                    case UserFollowTypeCode::TYPE_BANK_DEBIT:
                        $info['debit_card_submit'] = $i['total'];
                        break;
                    case UserFollowTypeCode::TYPE_BANK_CREDIT:
                        $info['credit_card_submit'] = $i['total'];
                        break;
                    case UserFollowTypeCode::TYPE_CERT_PHONE:
                        $info['phone_auth'] = $i['total'];
                        break;
                    case UserFollowTypeCode::TYPE_CERT_ZHIMA:
                        $info['zhima_auth'] = $i['total'];
                        break;
                    case UserFollowTypeCode::TYPE_CERT_APPLY:
                        $info['auth_submit'] = $i['total'];
                        break;
                    case UserFollowTypeCode::TYPE_CONFIRM_APPLY:
                        $info['confirm_submit'] = $i['total'];
                        break;
                    case UserFollowTypeCode::TYPE_BORROW_MONEY:
                        $info['want_loan'] = $i['total'];
                        break;
                    case UserFollowTypeCode::TYPE_REGRST_NUM:
                        $info['register_num'] = $i['total'];
                        break;
                    case UserFollowTypeCode::TYPE_PROTAL_PVUV:
                        $info['pv'] = $i['pv'];
                        $info['uv'] = $i['uv'];
                        break;
                }
            }
            $info = [
                'login_num' => empty($info['login_num']) ? 0 : $info['login_num'],
                'card_submit' => empty($info['card_submit']) ? 0 : $info['card_submit'],
                'face_submit' => empty($info['face_submit']) ? 0 : $info['face_submit'],
                'contact_submit' => empty($info['contact_submit']) ? 0 : $info['contact_submit'],
                'debit_card_submit' => empty($info['debit_card_submit']) ? 0 : $info['debit_card_submit'],
                'credit_card_submit' => empty($info['credit_card_submit']) ? 0 : $info['credit_card_submit'],
                'phone_auth' => empty($info['phone_auth']) ? 0 : $info['phone_auth'],
                'zhima_auth' => empty($info['zhima_auth']) ? 0 : $info['zhima_auth'],
                'auth_submit' => empty($info['auth_submit']) ? 0 : $info['auth_submit'],
                'confirm_submit' => empty($info['confirm_submit']) ? 0 : $info['confirm_submit'],
                'register_num' => empty($info['register_num']) ? 0 : $info['register_num'],
                'want_loan' => empty($info['want_loan']) ? 0 : $info['want_loan'],
                'pv' => empty($info['pv']) ? 0 : $info['pv'],
                'uv' => empty($info['uv']) ? 0 : $info['uv']
            ];
            $format_data = UserFollow::formatPercentData($info);

            $data[$k]['type_total'] = json_encode($format_data);
            $data[$k]['channel'] = $k;
            if ($k === 0) {
                $data[$k]['channel_name'] = 'APP';
            } else {
                $settingSource = DB::connection('backend')->table('setting_sources')->where('source_id', $k)->first();
                $data[$k]['channel_name'] = !empty($settingSource->source_name) ? $settingSource->source_name : '';
            }
            $data[$k]['date'] = date('Y-m-d',$yesterday_time);
            unset($info);
            unset($format_data);
        }


        try {
            DB::beginTransaction();
            DB::table('user_follow_cache_day')->insert($data);
            DB::commit();
            Log::debug('埋点消费成功数据-' . count($data));

            return $sql;
        } catch (\Exception $e) {
            Log::debug('埋点消费失败-' . $e->getMessage());
            DB::rollBack();

            return false;
        }

    }

    /**
     * 获取指定时间内的数据
     * @param string $start_time
     * @param string $end_time
     * @param string string $channel
     * @return mixed
     */
    public static function getData($start_time, $end_time, $channel = '')
    {
        $followCache = new UserFollowCacheDay();
        if (!$channel) {
            $result = $followCache->where('date', '>=', $start_time)->where('date', '<=', $end_time)->orderBy('channel')->orderBy('date')->get()->toArray();
        } else {
            $channelArr = array_filter(explode(',', trim($channel)));
            $result = $followCache->where('date', '>=', $start_time)->where('date', '<=', $end_time)->whereIn('channel', $channelArr)->orderBy('channel')->orderBy('date')->get()->toArray();
        }

        return $result;
    }

}
